<template>
  <div
    class="page_body"
    v-loading.fullscreen.lock="loadingKey"
    :element-loading-text="loadingText"
  >
    <!-- 面包屑 -->
    <el-row>
      <el-col :span="24" class="page_box_top">
        <i class="el-icon-s-fold"></i>
        <el-breadcrumb separator="/" class="page_box_top_nav">
          <el-breadcrumb-item class="breadcrumb_active_item"
            >用户管理</el-breadcrumb-item
          >
        </el-breadcrumb>
      </el-col>
    </el-row>
    <el-row>
      <div class="user_manager_content">
        <!-- 按钮栏 -->
        <el-row>
          <el-col :span="24">
            <div class="user_manager_top">
              <el-button
                size="mini"
                type="primary"
                @click="addFn()"
                v-if="userType == 0"
                >新增</el-button
              >
            </div>
          </el-col>
        </el-row>
        <!-- 数据列表 -->
        <div v-if="userListData != undefined && userListData.length > 0">
          <el-row>
            <el-col :span="24">
              <el-table
                :data="userListData"
                border
                size="mini"
                style="width: 100%"
                :cell-style="cellStyleFn"
              >
                <el-table-column
                  type="index"
                  label="序号"
                  width="50"
                  align="center"
                >
                </el-table-column>

                <el-table-column
                  prop="username"
                  label="用户名称"
                  min-width="250"
                  align="center"
                ></el-table-column>

                <el-table-column
                  prop="phone"
                  label="手机号"
                  min-width="140"
                  align="center"
                ></el-table-column>

                <el-table-column
                  prop="type"
                  label="身份"
                  min-width="100"
                  align="center"
                  :formatter="formatterTypeFn"
                ></el-table-column>

                <el-table-column
                  prop="status"
                  label="状态"
                  min-width="100"
                  align="center"
                  :formatter="formatterStatusFn"
                ></el-table-column>

                <el-table-column
                  label="操作"
                  v-if="userType == 0"
                  width="240"
                  align="center"
                >
                  <template slot-scope="scope">
                    <el-button
                      size="mini"
                      type="primary"
                      @click="editFn(scope.$index, scope.row)"
                    >
                      修改
                    </el-button>

                    <el-button
                      size="mini"
                      type="danger"
                      @click="deleteFn(scope.$index, scope.row)"
                    >
                      删除
                    </el-button>

                    <el-button
                      size="mini"
                      type="info"
                      v-if="scope.row.status == 1"
                      @click="changeStatus(scope.$index, scope.row)"
                    >
                      禁用
                    </el-button>
                    <el-button
                      size="mini"
                      type="primary"
                      v-if="scope.row.status == 2"
                      @click="changeStatus(scope.$index, scope.row)"
                    >
                      启用
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <div class="user_manager_pagination">
                <el-pagination
                  @size-change="listSizeChange"
                  @current-change="listCurrentChange"
                  :current-page="currentPage"
                  :page-sizes="pageSizes"
                  :page-size="pageSize"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="total"
                >
                </el-pagination>
              </div>
            </el-col>
          </el-row>
        </div>
        <el-row v-else>
          <el-empty description="暂无数据"></el-empty>
        </el-row>
        <!-- 弹窗 -->
        <el-dialog
          :title="dialogTitle"
          :visible.sync="dialogVisible"
          :close-on-click-modal="false"
          width="400px"
        >
          <el-form
            ref="dialogDetailForm"
            :model="detailFormData"
            :rules="detailFormRules"
          >
            <el-form-item
              label="用户名称"
              prop="username"
              :label-width="formLabelWidth"
            >
              <el-input
                size="small"
                style="width: 200px"
                v-model="detailFormData.username"
              ></el-input>
            </el-form-item>

            <el-form-item
              label="手机号"
              prop="phone"
              :label-width="formLabelWidth"
            >
              <el-input
                type="number"
                size="small"
                style="width: 200px"
                v-model="detailFormData.phone"
                :disabled="dialogBtnKey == 2"
              ></el-input>
            </el-form-item>

            <el-form-item
              label="身份"
              prop="type"
              :label-width="formLabelWidth"
            >
              <el-radio v-model="detailFormData.type" label="0"
                >超级管理员</el-radio
              >
              <el-radio v-model="detailFormData.type" label="1"
                >普通管理员</el-radio
              >
              <el-radio v-model="detailFormData.type" label="2"
                >管理员仅查看</el-radio
              >
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button size="small" @click="dialogclose()">取 消</el-button>
            <el-button
              size="small"
              type="primary"
              @click="dialogDetailFormSubmit()"
              v-if="userType == 0"
              >确 定</el-button
            >
          </span>
        </el-dialog>
      </div>
    </el-row>
  </div>
</template>
<style src="../../assets/css/user/userManager.css" scoped></style>

<script>
export default {
  name: "UserManager",
  components: {},
  data() {
    return {
      userType: this.$store.state.loginUserType == "ADMINLOGINUSERCH" ? 0 : 1, // 用户类型;1. 普通; 0. 超级;
      baseAPIUrl: this.$store.state.baseAPIUrl,
      userListData: [], // 数据列表
      currentPage: 1, // 当前页
      pageSizes: [10, 20, 50, 100], // 可选页容量
      pageSize: 10, // 当前页容量
      total: 0, // 总条数
      searchKey: "", // 搜索关键词
      loadingKey: false,
      loadingText: "",
      dialogTitle: "", // 弹窗标题
      dialogBtnKey: "", // 弹窗确认按钮控制; 1. 新增确认;2. 修改确认;
      dialogVisible: false, // 弹窗显示
      detailFormData: {
        id: "",
        username: "", // 用户名
        phone: "", // 手机号
        type: "", // 身份
      }, // 部门弹窗数据
      detailFormRules: {
        username: [
          { required: true, message: "请输入用户名称", trigger: "blur" },
          {
            min: 2,
            max: 10,
            message: "长度在 2 到 10 个字符",
            trigger: "blur",
          },
        ],
        phone: [
          { required: true, validator: this.validatePhone, trigger: "blur" },
        ],
        type: [{ required: true, message: "请选择身份", trigger: "change" }],
      },
      formLabelWidth: "90px",
      userTypeList: [
        {
          key: 0,
          value: "超级管理员",
        },
        {
          key: 1,
          value: "普通管理员",
        },
        {
          key: 2,
          value: "管理员仅查看",
        },
      ], //用户身份字典
      statusList: [
        {
          key: 1,
          value: "启用",
        },
        {
          key: 2,
          value: "禁用",
        },
      ], //用户状态字典
    };
  },
  created: function () {
    this.getListDataFn();
  },
  methods: {
    // 获取列表数据
    getListDataFn: function () {
      let that = this;
      let url = "/admin/adminusers/index";
      let data = {
        page: this.currentPage,
        perPage: this.pageSize,
        keywords: this.searchKey,
      };
      that.loadingText = "加载中...";
      that.loadingKey = true;
      this.axios
        .post(url, data)
        .then((response) => {
          that.loadingKey = false;
          if (response.code == 0) {
            that.userListData = response.list;
            that.total = response.total_count;
          } else {
            that.$message.error(response.msg);
          }
        })
        .catch(function (error) {
          that.loadingKey = false;
          console.log(error);
        });
    },
    // 新增
    addFn: function () {
      let that = this;
      this.dialogTitle = "新增用户";
      this.dialogBtnKey = 1;
      this.detailFormData = {
        id: "",
        username: "",
        phone: "",
        type: "",
      };
      this.$nextTick(function () {
        that.dialogVisible = true;
        that.$refs.dialogDetailForm.clearValidate();
      });
    },
    // 修改
    editFn: function (index, row) {
      this.dialogTitle = "修改用户";
      this.dialogBtnKey = 2;
      this.detailFormData = {
        id: row.id,
        username: row.username,
        phone: row.phone,
        type: row.type + "",
      };
      this.$nextTick(function () {
        this.dialogVisible = true;
      });
    },

    // 弹窗保存
    dialogDetailFormSubmit: function () {
      let that = this;
      let url = "";
      let data = {};
      if (this.dialogBtnKey == 2) {
        url = "/admin/adminusers/update";
        data = {
          id: this.detailFormData.id,
          username: this.detailFormData.username,
          type: this.detailFormData.type,
        };
      } else {
        url = "/admin/adminusers/register";
        data = {
          username: this.detailFormData.username,
          phone: this.detailFormData.phone,
          type: this.detailFormData.type,
        };
      }
      this.$refs.dialogDetailForm.validate((valid) => {
        if (!valid) {
          return false;
        } else {
          that
            .$confirm("确认提交?", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
            })
            .then(() => {
              that.loadingText = "处理中...";
              that.loadingKey = true;
              that.axios
                .post(url, data)
                .then((response) => {
                  that.loadingKey = false;
                  if (response.code == 0) {
                    if (that.dialogBtnKey == 2) {
                      that.$message.success("修改成功");
                    } else {
                      that.$message.success("新增成功");
                    }
                    that.dialogclose();
                    that.getListDataFn();
                  } else {
                    that.$message.error(response.msg);
                  }
                })
                .catch(function (error) {
                  that.loadingKey = false;
                  console.log(error);
                });
            })
            .catch(() => {});
        }
      });
    },

    // 关闭弹窗
    dialogclose: function () {
      this.dialogVisible = false;
    },

    // 删除
    deleteFn: function (index, row) {
      let that = this;
      this.$confirm("确认删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      }).then(() => {
        let url = "/admin/adminusers/destroy";
        let data = {
          id: row.id,
        };
        that.loadingText = "处理中...";
        that.loadingKey = true;
        that.axios
          .post(url, data)
          .then((response) => {
            that.loadingKey = false;
            if (response.code == 0) {
              that.$message.success("删除成功");
              let next = that.currentPage - 1;
              if (that.userListData.length == 1) {
                that.currentPage = next >= 1 ? next : 1;
              }
              that.getListDataFn();
            } else {
              that.$message.error(response.msg);
            }
          })
          .catch(function (error) {
            that.loadingKey = false;
            console.log(error);
          });
      });
    },
    // 页容量改变
    listSizeChange: function (val) {
      this.currentPage = 1;
      this.pageSize = val;
      this.getListDataFn();
    },
    // 当前页改变
    listCurrentChange: function (val) {
      this.currentPage = val;
      this.getListDataFn();
    },
    // 搜索按钮
    searchFn: function () {
      this.currentPage = 1;
      this.getListDataFn();
    },
    // 身份格式化
    formatterTypeFn: function (row) {
      let type = row.type;
      let text = "";
      this.userTypeList.forEach(function (item) {
        if (item.key == type) {
          text = item.value;
        }
      });
      return text;
    },
    // 状态格式化
    formatterStatusFn: function (row) {
      let status = row.status;
      let text = "";
      this.statusList.forEach(function (item) {
        if (item.key == status) {
          text = item.value;
        }
      });
      return text;
    },
    // 手机校验
    validatePhone: function (rule, value, callback) {
      if (value === "") {
        callback(new Error("请输入手机号"));
      } else {
        let telText =
          /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-9])\d{8}$/;
        if (!telText.test(value)) {
          callback(new Error("手机号格式不正确"));
        } else {
          callback();
        }
      }
    },
    // 设置单元格字体颜色
    cellStyleFn: function ({ row, columnIndex }) {
      let style = "";
      if (columnIndex == 3) {
        if (row.type == 1) {
          style = "color: #8ECF5F";
        } else {
          style = "color: #F6705E";
        }
      }
      if (columnIndex == 4) {
        if (row.status == 1) {
          style = "color: #8ECF5F";
        } else {
          style = "color: #F6705E";
        }
      }
      return style;
    },
    // 禁用/启用
    changeStatus: function (index, row) {
      let that = this;
      let url = "/admin/adminusers/changeStatus";
      let data = {
        id: row.id,
      };
      let text = "";
      if (row.status == 2) {
        text = "启用";
        data.status = 1;
      } else {
        text = "禁用";
        data.status = 2;
      }
      this.$confirm("确认" + text + "该用户?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      }).then(() => {
        that.loadingText = "处理中...";
        that.loadingKey = true;
        that.axios
          .post(url, data)
          .then((response) => {
            that.loadingKey = false;
            if (response.code == 0) {
              that.$message.success(text + "成功");
              that.getListDataFn();
            } else {
              that.$message.error(response.msg);
            }
          })
          .catch(function (error) {
            that.loadingKey = false;
            console.log(error);
          });
      });
    },
  },
};
</script>
